<template>
    <div class="datasource-container">
        <el-card class="action-card">
            <template #header>
                <div class="card-header">
                    <h3>数据源管理</h3>
                    <el-button type="primary" @click="handleAddSource">
                        添加数据源
                    </el-button>
                </div>
            </template>
            
            <el-table :data="dataSources" v-loading="loading" style="width: 100%">
                <el-table-column prop="name" label="名称" />
                <el-table-column prop="type" label="类型">
                    <template #default="scope">
                        <el-tag :type="getSourceTypeTag(scope.row.type)">
                            {{ getSourceTypeName(scope.row.type) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="is_active" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.is_active ? 'success' : 'info'">
                            {{ scope.row.is_active ? '已激活' : '未激活' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间">
                    <template #default="scope">
                        {{ formatDate(scope.row.created_at) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250">
                    <template #default="scope">
                        <el-button-group>
                            <el-button 
                                type="primary" 
                                :icon="Edit"
                                @click="handleEdit(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button 
                                type="success" 
                                :icon="Connection"
                                @click="handleTest(scope.row)"
                                :loading="scope.row.testing"
                            >
                                测试连接
                            </el-button>
                            <el-button 
                                type="danger" 
                                :icon="Delete"
                                @click="handleDelete(scope.row)"
                            >
                                删除
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加/编辑数据源对话框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="isEdit ? '编辑数据源' : '添加数据源'"
            width="600px"
        >
            <el-form 
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入数据源名称" />
                </el-form-item>
                
                <el-form-item label="类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择数据源类型" style="width: 100%">
                        <el-option label="微博" value="weibo" />
                        <el-option label="Twitter" value="twitter" />
                        <el-option label="Facebook" value="facebook" />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="认证信息">
                    <template v-if="form.type === 'weibo'">
                        <el-form-item label="使用代理" prop="credentials.use_proxy">
                            <el-switch v-model="form.credentials.use_proxy" />
                        </el-form-item>
                        <template v-if="form.credentials.use_proxy">
                            <el-form-item label="代理地址" prop="credentials.proxy.http">
                                <el-input v-model="form.credentials.proxy.http" placeholder="http://127.0.0.1:7890" />
                            </el-form-item>
                        </template>
                    </template>
                    
                    <template v-if="form.type === 'twitter'">
                        <el-form-item label="API密钥" prop="credentials.consumer_key">
                            <el-input v-model="form.credentials.consumer_key" show-password />
                        </el-form-item>
                        <el-form-item label="API密钥密文" prop="credentials.consumer_secret">
                            <el-input v-model="form.credentials.consumer_secret" show-password />
                        </el-form-item>
                        <el-form-item label="访问令牌" prop="credentials.access_token">
                            <el-input v-model="form.credentials.access_token" show-password />
                        </el-form-item>
                        <el-form-item label="令牌密文" prop="credentials.access_token_secret">
                            <el-input v-model="form.credentials.access_token_secret" show-password />
                        </el-form-item>
                    </template>
                    
                    <template v-if="form.type === 'facebook'">
                        <el-form-item label="访问令牌" prop="credentials.access_token">
                            <el-input v-model="form.credentials.access_token" show-password />
                        </el-form-item>
                    </template>
                </el-form-item>
                
                <el-form-item label="状态" prop="is_active">
                    <el-switch v-model="form.is_active" />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Connection } from '@element-plus/icons-vue'
import { analysisApi } from '@/api/analysis'

const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const dataSources = ref([])
const formRef = ref(null)

// 表单数据
const form = ref({
    name: '',
    type: '',
    credentials: {
        use_proxy: false,
        proxy: {
            http: '',
            https: ''
        },
        consumer_key: '',
        consumer_secret: '',
        access_token: '',
        access_token_secret: ''
    },
    is_active: true
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择数据源类型', trigger: 'change' }
    ]
}

// 获取数据源列表
const fetchDataSources = async () => {
    loading.value = true
    try {
        const response = await analysisApi.getDataSources()
        dataSources.value = response.results || []
    } catch (error) {
        ElMessage.error('获取数据源列表失败')
        console.error('Error fetching data sources:', error)
    } finally {
        loading.value = false
    }
}

// 添加数据源
const handleAddSource = () => {
    isEdit.value = false
    form.value = {
        name: '',
        type: '',
        credentials: {
            use_proxy: false,
            proxy: {
                http: '',
                https: ''
            }
        },
        is_active: true
    }
    dialogVisible.value = true
}

// 编辑数据源
const handleEdit = (row) => {
    isEdit.value = true
    form.value = { ...row }
    dialogVisible.value = true
}

// 测试连接
const handleTest = async (row) => {
    row.testing = true
    try {
        const response = await analysisApi.testDataSourceConnection(row.id)
        ElMessage.success(response.message || '连接测试成功')
    } catch (error) {
        ElMessage.error('连接测试失败')
    } finally {
        row.testing = false
    }
}

// 删除数据源
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该数据源吗？删除后无法恢复。',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        await analysisApi.deleteDataSource(row.id)
        ElMessage.success('删除成功')
        fetchDataSources()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        submitting.value = true
        
        if (isEdit.value) {
            await analysisApi.updateDataSource(form.value.id, form.value)
            ElMessage.success('更新成功')
        } else {
            await analysisApi.createDataSource(form.value)
            ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        fetchDataSources()
    } catch (error) {
        console.error('Error submitting form:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    } finally {
        submitting.value = false
    }
}

// 获取数据源类型标签样式
const getSourceTypeTag = (type) => {
    const types = {
        weibo: 'primary',
        twitter: 'success',
        facebook: 'info'
    }
    return types[type] || 'default'
}

// 获取数据源类型名称
const getSourceTypeName = (type) => {
    const types = {
        weibo: '微博',
        twitter: 'Twitter',
        facebook: 'Facebook'
    }
    return types[type] || type
}

// 格式化日期
const formatDate = (date) => {
    return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
    fetchDataSources()
})
</script>

<style scoped>
.datasource-container {
    padding: 20px;
}

.action-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
}

:deep(.el-dialog__body) {
    padding-top: 20px;
}

.el-button-group {
    display: flex;
    gap: 8px;
}

@media screen and (max-width: 768px) {
    .datasource-container {
        padding: 12px;
    }
    
    .el-button-group {
        flex-direction: column;
    }
}
</style> 